package com.dream.root.user.config.aop;

import com.alibaba.fastjson.JSONObject;
import com.dream.root.common.annotation.HttpApi;
import com.dream.root.common.context.BaseContextHandler;
import com.dream.root.common.exception.BaseException;
import com.dream.root.common.response.BaseResponse;
import com.dream.root.common.sequence.Sequence;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * ApiAspect Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 28/07/2018
 * Time: 02:55
 * Description: ApiAspect
 */
@Aspect
@Component
@Slf4j
public class ApiAspect {

    @Resource
    private Sequence sequence;

    @Pointcut("@annotation(com.dream.root.common.annotation.HttpApi)")
    public void allMethod() {
    }

    //前置
    @Before("allMethod()")
    public void beforeExec(JoinPoint joinPoint) {
    }

    //环绕
    @Around("allMethod()")
    public Object aroundExec(ProceedingJoinPoint joinPoint) {
        BaseContextHandler.set("startTime", System.currentTimeMillis());
        BaseResponse result = new BaseResponse();
        long uuid = sequence.nextId();  //流水号
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method method = ms.getMethod();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String param = JSONObject.toJSONString(request.getParameterMap());  //入参
        HttpApi httpApi = method.getAnnotation(HttpApi.class);
        String functionId = httpApi.functionId();
        try {
            result = (BaseResponse) joinPoint.proceed();
        } catch (Throwable e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            if (e instanceof BaseException) {
                BaseException baseException = (BaseException) e;
                result = new BaseResponse(baseException.getBaseResponseCode());
            } else result = new BaseResponse(e);
        }
        long time = System.currentTimeMillis() - (Long) BaseContextHandler.get("startTime");
        log.info("消耗时间：" + time);
        result.setUuid(uuid);
        return result;
    }
}
